import React from 'react';
import {Router, Route,hashHistory,IndexRoute, Redirect} from 'react-router';
import moment from 'moment';
import ReactDOM from 'react-dom';
require('es6-promise').polyfill();
require('isomorphic-fetch');
export default class OrderHourChoose extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            year: moment().format("YYYY"),
            month: moment().format("MM"),
            hour: moment().format("HH"),
            cal: moment().format("YYYY-MM-DD"),
            getTimeState:this.getTimeState.bind(this),
            arrHtmls:[],
            currentIndex:0,
            curTimeIndex:'',
            getDay:moment().format("YYYY-MM-DD"),
            flag:false,
            weekDay: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            times:['08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30',
                '14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00']
        }
    }

    //触发右箭头 日期递增
    getForwardDay() {
        var currentFirstDay = moment(this.state.cal).add(7, 'days').format("YYYY-MM-DD");
        this.changState(currentFirstDay);
        var getDay=moment(currentFirstDay).add(this.state.currentIndex, 'days').format("YYYY-MM-DD");
        this.changeGetDay(getDay);
         console.log(getDay+"you");
        this.getTimeState(getDay);
    }

    //cal,表示变化的日期
    changState(cal) {
        return this.setState({
            cal: cal,
            year: moment(cal).format("YYYY"),
            month: moment(cal).format("MM"),
        })
    }
    //选择的日期
   changeGetDay(getDay){
        this.setState({
            getDay:getDay
        })
    }

    //触发左箭头  日期递减
    getBackward() {
        var currentFirstDay = moment(this.state.cal).add(-7, 'days').format("YYYY-MM-DD");
        var nowDate = moment().format("YYYY-MM-DD");
        if (currentFirstDay < nowDate) {
            currentFirstDay = nowDate;
        }
        this.changState(currentFirstDay);
        var getDay=moment(currentFirstDay).add(this.state.currentIndex, 'days').format("YYYY-MM-DD")
        this.changeGetDay(getDay);
        console.log(getDay+"zuo");
        this.getTimeState(getDay);
    }

    //即将渲染页面  初次调用方法
    componentWillMount(){
        let userid= localStorage.getItem('userid');
        if(userid==null || userid==''){
            hashHistory.push({
                pathname:"/login"
            })
        }else {
            this.getTimeState(this.state.cal);
        }

    }


    /*1.获取到数据，
     2.在循环 时间的方法中调用1
     3.判端循环 的数据和获取到的数据值比较，如果是 true就是约满，否则就可以越
     */
      getTimeState(date){
          fetch('date.json',
              {
                  method: 'get',
                  headers: {
                      'Accept': 'application/json',
                      "Content-Type": "application/json"
                  },
              }
          ).then(function(response) {
              return response.json();
          }).then((json)=>{
              this.setState({
                  arrHtmls:this.getTime(this.state.times,json)
              });

          }).catch(function(ex) {
              console.log('parsing failed', ex)
          })
      }



    //判断时间是否可以接单
    getTime(times,data){
          var arrHtml=[];
        for(var i=0;i<times.length;i++){
            for(var key in data)
            {
                if( times[i]==key ){
                    var eachHtml=times[i];
                     if(data[key]){
                         arrHtml.push({"checked":true,"eachHtml":eachHtml})
                     }else {
                         arrHtml.push({"checked":false,"eachHtml":eachHtml})
                     }
                }
            }
        }
        return arrHtml;
    }
    //给本元素增加类，其余删除类   day
    changeClassDay(e){
        var index=e.target.getAttribute('data-index');
        this.setState({
            currentIndex:index
        })

        var getDay = moment(this.state.cal).add(parseInt(index), 'days').format("YYYY-MM-DD");
        this.changeGetDay(getDay);
         console.log(getDay+"lei");
         this.getTimeState(getDay);

    }
    //给本元素增加类，其余删除类   time
    changeClassTime(index){
        this.setState({
            curTimeIndex:index,
        })

        let text=this.refs.time.childNodes[index].innerText;

        let hour =moment(text, "HH:mm").format("HH:mm");
        this.setState({
            flag:true,
            hour:hour
        })

    }
    //确定提交
     order(){
        var timeStr= this.state.getDay+" "+this.state.hour;
        var dateTime=moment(timeStr).format("YYYY-MM-DD HH:mm");
        console.log(localStorage.getItem("userAddress"));
        var obj={
            dateTime:dateTime,
            serverNum:sessionStorage.getItem("serverNum"),
            serverHour:sessionStorage.getItem("serverHour"),
            serverAddress:localStorage.getItem("userAddress"),
            order_type:sessionStorage.getItem("order_type"),
            order_price:sessionStorage.getItem("order_price")

        }
        fetch('date.json',
            {
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    "Content-Type": "application/json"
                },
                body:JSON.stringify(obj),

            }
        ).then(function(response) {
            return response.json();
        }).then((json)=>{
             console.log(json);

        }).catch(function(ex) {
            console.log('parsing failed', ex)
        })
     }


    render() {

        return (
            <div style={{height: '100%', backgroundColor: 'rgb(239, 239, 244)'}}>
                <div className="calendar">
                    <h3>{this.state.year}</h3>
                    <ul className="day-change clearfloat">
                        <li id="left_arrow" onClick={this.getBackward.bind(this)}><span>&lt;</span></li>
                        <li>{this.state.month}</li>
                        <li id="right_arrow" onClick={this.getForwardDay.bind(this)}><span>&gt;</span></li>
                    </ul>
                    <GetWeek cal={this.state.cal} weekDay={this.state.weekDay}/>
                </div>

                <GetDay value={this.state.cal}  currentIndex={this.state.currentIndex} changeClassDay={this.changeClassDay.bind(this)} getTimeState={this.getTimeState.bind(this)}/>

                <ul className="calendar-hour clearfloat" id="calendar-hour" ref="time">
                    {
                        this.state.arrHtmls.map((item,index)=>{

                           if(item.checked){
                               return(
                                   <li className="calendar-notime" key={index}><span>{item.eachHtml}</span><span>约满</span></li>
                               )
                           }
                           return(
                               <li id={index} onClick={this.changeClassTime.bind(this,index)} className={this.state.curTimeIndex==index?"time-checked":""} key={index}>{item.eachHtml}</li>
                           )

                        })
                    }

                </ul>
                <div className="calendar-button">
                    <input onClick={this.order.bind(this)} className={(this.state.flag==true?'button-checked':'')+" button"} type="button" value='确定'/>
                </div>
            </div>
        )
    }
}

//遍历天
function GetDay(cal) {
    var dateArr = [];
    var d = cal.value;
    var currentIndex=cal.currentIndex;
    var getTimeState=cal.getTimeState;
    var changeClassDay=cal.changeClassDay;


    for (let i = 0; i < 7; i++) {
        var day = moment(d).add(i, 'days').format("DD");
        var date = moment(d).add(i, 'days').format("YYYY-MM-DD");
        dateArr.push({"day":day,"date":date});
    }

     return  (
         <ul className="calendar-day clearfloat" id="calendar-day">
            {dateArr.map((item,index) => {

              return(
                  <li onClick={getTimeState} key={item.date}>
                      <span onClick={changeClassDay} data-index={index} id={item.date} className={currentIndex==index?'checked':''} >{item.day}</span>
                  </li>
              )

                })
            }
        </ul>
     )
}
//遍历周
function GetWeek(props) {
    let cal=props.cal;
    let weekDay=props.weekDay;
    var weekArr=[];

    let nowDate= moment().format("YYYY-MM-DD");
    let currentDate=moment(cal).format("YYYY-MM-DD");

    for(let i=0;i<7;i++){
        let week=parseInt(moment(cal).add(i,"days").format("d"));
        weekArr.push(weekDay[week]);
    }
    return(
        <div className="calendar-week">
            {
                weekArr.map((item,index)=>{
                    if(index==0){
                        return <span  key={index}>{nowDate==currentDate?"今天":item}</span>
                    }
                    else if(index==1){
                        return <span key={index}>{nowDate==currentDate?"明天":item}</span>

                    }else {
                        return <span key={index}>{item}</span>
                    }

                })
            }
        </div>
    )
}



